# -*- coding: utf-8 -*-

from rest_framework import serializers
from apps.tms.models import *
from apps.sys.models import User
from rest_framework.serializers import SerializerMethodField
from core.serializers import CustomModelSerializer
from core.relations import BaseNameWritableRelatedField, UserNameWritableRelatedField


class JobListSerializer(CustomModelSerializer):
    """
    任务列表-序列化器
    """

    job_execution = SerializerMethodField()

    def get_job_execution(self, instance):
        job_execution = JobExecution.objects.filter(job=instance.id).first()
        return str(job_execution.id) if job_execution else ""

    class Meta:
        model = Job
        fields = "__all__"
        read_only_fields = ["id"]


class JobSerializer(CustomModelSerializer):
    """
    任务详情-序列化器
    """

    product = BaseNameWritableRelatedField()
    owner = UserNameWritableRelatedField()
    env = BaseNameWritableRelatedField()
    tcs = BaseNameWritableRelatedField(many=True)
    nodes = BaseNameWritableRelatedField(many=True)
    plugin = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    job_execution = SerializerMethodField()

    def get_job_execution(self, instance):
        job_execution = JobExecution.objects.filter(job=instance.id).first()
        return str(job_execution.id) if job_execution else ""

    class Meta:
        model = Job
        fields = "__all__"
        read_only_fields = ["id"]


class JobExecutionSerializer(CustomModelSerializer):
    """
    任务执行记录-序列化器
    """

    class Meta:
        model = JobExecution
        fields = "__all__"
        read_only_fields = ["id"]


class JobLogListSerializer(CustomModelSerializer):
    """
    用例日志-序列化器
    """

    job = BaseNameWritableRelatedField()
    job_type = serializers.CharField(source="job.type")
    executor_name = serializers.SerializerMethodField(read_only=True)
    analyser_name = serializers.SerializerMethodField(read_only=True)
    module_name = serializers.SerializerMethodField(read_only=True)

    def get_module_name(self, instance):
        return instance.module.name

    def get_executor_name(self, instance):
        if not hasattr(instance, "executor"):
            return None
        queryset = (
            User.objects.filter(id=instance.executor)
            .values_list("name", flat=True)
            .first()
        )
        if queryset:
            return queryset
        return None

    def get_analyser_name(self, instance):
        if not hasattr(instance, "analyser"):
            return None
        queryset = (
            User.objects.filter(id=instance.analyser)
            .values_list("name", flat=True)
            .first()
        )
        if queryset:
            return queryset
        return None

    class Meta:
        model = JobLog
        fields = "__all__"
        read_only_fields = ["id"]


class JobLogSerializer(CustomModelSerializer):
    """
    用例日志-序列化器
    """

    job = JobSerializer()
    job_execution = JobExecutionSerializer()

    class Meta:
        model = JobLog
        fields = "__all__"
        read_only_fields = ["id"]


class JobLogCreateUpdateSerializer(CustomModelSerializer):
    """
    用例日志-序列化器
    """

    job = BaseNameWritableRelatedField()

    class Meta:
        model = JobLog
        fields = "__all__"
        read_only_fields = ["id"]


class JobPluginSerializer(CustomModelSerializer):

    file = serializers.SerializerMethodField(read_only=True)

    def get_file(self, instance):
        return "/media/" + str(instance.file)

    class Meta:
        model = JobPlugin
        fields = "__all__"

    def create(self, validated_data):
        validated_data["name"] = str(self.initial_data.get("file"))
        validated_data["file"] = self.initial_data.get("file")
        validated_data["size"] = self.initial_data.get("file").size
        return super().create(validated_data)
